<template>
  <view class="cart">
    <view class="search">
      <u-search
        placeholder="输入商品"
        v-model="inp"
        @custom="handleAdd"
      ></u-search>
    </view>

    <u-line color="red" />

    <u-table>
      <u-tr>
        <u-th>商品</u-th>
        <u-th>操作</u-th>
      </u-tr>
      <u-tr v-for="(item, index) in list" :key="item.name">
        <u-td>{{ item.name }}</u-td>
        <u-td>
          <view class="u-flex">
            <button @click="handleNumUpdate(-1, index)">-</button>
            <view>{{ item.count }}</view>
            <button @click="handleNumUpdate(+1, index)">+</button>
          </view>
        </u-td>
      </u-tr>
    </u-table>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 输入框的值
      inp: "",
      // 商品数组列表
      list: [],
    };
  },
  methods: {
    // 点击确定按钮
    handleAdd() {
      const index = this.list.findIndex((v) => v.name === this.inp);

      if (index === -1) {
        // 没有找到 执行添加
        this.list.push({ name: this.inp, count: 1 });
      } else {
        this.list[index].count++;
      }
    },
    // 数量编辑
    handleNumUpdate(num, index) {
      this.list[index].count += num;
    },
  },
};
</script>

<style></style>
